import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { apiService } from '@/services/api'

export const useCoursesStore = defineStore('courses', () => {
  const courses = ref([])

  // 初始化课程数据
  const initializeCourses = async () => {
    try {
      courses.value = await apiService.getCourses()
    } catch (error) {
      console.error('初始化课程数据失败:', error)
    }
  }

  // 添加课程
  const addCourse = async (courseData) => {
    try {
      const newCourse = await apiService.createCourse({
        ...courseData,
        enrolled: 0,
        status: 'open'
      })
      courses.value.push(newCourse)
      return newCourse
    } catch (error) {
      console.error('添加课程失败:', error)
      throw error
    }
  }

  const updateCourse = async (courseId, updates) => {
    try {
      const updatedCourse = await apiService.updateCourse(courseId, updates)
      if (updatedCourse) {
        const index = courses.value.findIndex(c => c.id === courseId)
        if (index !== -1) {
          courses.value[index] = updatedCourse
        }
      }
      return updatedCourse
    } catch (error) {
      console.error('更新课程失败:', error)
      throw error
    }
  }

  const deleteCourse = async (courseId) => {
    try {
      await apiService.deleteCourse(courseId)
      courses.value = courses.value.filter(c => c.id !== courseId)
      return true
    } catch (error) {
      console.error('删除课程失败:', error)
      throw error
    }
  }

  // 学生选课
  const enrollStudent = async (courseId, studentId) => {
    try {
      const course = courses.value.find(c => c.id === courseId)
      if (course && course.enrolled < course.capacity && course.status === 'open') {
        // 更新课程选课人数
        const updatedCourse = await apiService.updateCourse(courseId, {
          enrolled: course.enrolled + 1,
          status: course.enrolled + 1 >= course.capacity ? 'full' : 'open'
        })
        
        // 更新本地状态
        const index = courses.value.findIndex(c => c.id === courseId)
        if (index !== -1) {
          courses.value[index] = updatedCourse
        }
        
        return true
      }
      return false
    } catch (error) {
      console.error('选课失败:', error)
      throw error
    }
  }

  // 根据ID获取课程
  const getCourseById = (courseId) => {
    return courses.value.find(c => c.id === courseId)
  }

  // 根据教师名称获取课程
  const getCoursesByTeacher = (teacherName) => {
    return courses.value.filter(c => c.teacher === teacherName)
  }

  // 获取可选课程（未满员且状态为open）
  const getAvailableCourses = () => {
    return courses.value.filter(c => c.status === 'open')
  }

  return {
    courses,
    initializeCourses,
    addCourse,
    updateCourse,
    deleteCourse,
    enrollStudent,
    getCourseById,
    getCoursesByTeacher,
    getAvailableCourses
  }
})